#!/usr/bin/env python2.7

import httplib, urllib
import sys
import serial

#print 'Number of arguments:', len(sys.argv), 'arguments.'
#print 'Argument List:', str(sys.argv)
# params = urllib.urlencode({'sensor_id': sys.argv[1], 'humidity': sys.argv[2], 'celcius': sys.argv[3]})
#if len(sys.argv) != 4:
#  exit()

sensor_id = 1

if len(sys.argv) < 3:
  print "missing args for serial port and host"
  exit()

ser = serial.Serial(sys.argv[1], 9600, timeout=10)
# throw out the first line until there is a proper data envelop (and checksum)
line = ser.readline()

i = 0
while i < 10:
  line = ser.readline().strip()
  print line

  humidity, degreesC = line.strip().split(',')

  params = urllib.urlencode({'sensor_id': sensor_id, 'humidity': humidity, 'celcius': degreesC})
  conn = httplib.HTTPConnection(sys.argv[2])
  conn.request("POST", "/post?sensor_id=1", params)
  response = conn.getresponse()
  print response.status, response.reason
  data = response.read()
  print data
  conn.close()
  i = i + 1

ser.close()
